package com.fw.leetcode.queue;

import com.fw.leetcode.LeetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 387. First Unique Character in a String
 *
 * Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
 *
 * Example 1:
 *  Input: s = "leetcode"
 *  Output: 0
 *
 * Example 2:
 *  Input: s = "loveleetcode"
 *  Output: 2
 *
 * Example 3:
 *  Input: s = "aabb"
 *  Output: -1
 *
 * Constraints:
 *  1 <= s.length <= 10^5
 *  s consists of only lowercase English letters.
 */
public class Num_0387 implements LeetCode {
    private interface Solution {
        int firstUniqChar(String s);

        default void assertEquals(String s, int expected) {
            if (firstUniqChar(s) != expected) {
                firstUniqChar(s);
            }
        }
    }

    private static class MyHashSolution implements Solution {

        @Override
        public int firstUniqChar(String s) {
            /*
             * 字符串中第一个唯一字符的索引位置
             * 1.哈希表存 字符出现的频次，再从头遍历字符串，首个频次为1的便是
             * 2.哈希表存 字符首次出现的索引，若重复出现标记索引为 -1，最后遍历非 -1 的最小的一个便是
             */
            HashMap<Character, Integer> map = new HashMap<>();
            for (char ch : s.toCharArray()) {
                map.put(ch, map.getOrDefault(ch, 0) + 1);
            }
            for (int i = 0; i < s.length(); i++) {
                if (map.get(s.charAt(i)) == 1) {
                    return i;
                }
            }
            return -1;
        }
    }

    private static class MyQueueSolution implements Solution {

        @Override
        public int firstUniqChar(String s) {
            /*
             * 字符串中第一个唯一字符的索引位置
             * 1.哈希表+队列
             */
            // 没必要这么复杂
            return -1;
        }
    }

    public static void main(String[] args) {
        Solution solution = new MyHashSolution();
        solution.assertEquals("leetcode", 0);
        solution.assertEquals("loveleetcode", 2);
        solution.assertEquals("aabb", -1);
    }
}
